package plugin

import (
	"dingbot/config"
	"dingbot/database"
	"dingbot/errhelp"
	"dingbot/tools"
	"io/ioutil"
	"net/http"

	"github.com/dingdinglz/dingtools/dingjson"
)

type PluginModal struct {
	Name   string `json:"name"`
	Enable bool   `json:"enable"`
}

func GetPlugins() []PluginModal {
	if !init_plugin_ok {
		return nil
	}
	var index int = 1
	var total int = 1
	token_use, _ := database.AuthEmail(config.GetConfig().PocketBase.User, config.GetConfig().PocketBase.Password)
	res_plugins := []PluginModal{}
	for index <= total {
		url := "http://127.0.0.1:" + config.GetConfig().Port.PocketBase + "/api/collections/plugins/records?page=" + tools.IntToString(index)

		req, _ := http.NewRequest("GET", url, nil)

		req.Header.Add("Authorization", "Admin "+token_use)

		res, _ := http.DefaultClient.Do(req)

		defer res.Body.Close()
		body, _ := ioutil.ReadAll(res.Body)
		j := dingjson.NewFromBytes(body)
		i, _ := j.GetInt("totalPages")
		total = int(i)
		j.ArrayEach(func(json *dingjson.DingJson) {
			i_add := PluginModal{}
			err := json.ConventToStruct(&i_add)
			errhelp.Tag(err, "Get Plugins")
			res_plugins = append(res_plugins, i_add)
		}, "items")
		index++
	}
	return res_plugins
}
